<template>
  <ContentWrap v-loading="formLoading">
    <el-tabs v-model="activeName">
      <el-tab-pane label="基本信息" name="basicInfo">
        <basic-info-form ref="basicInfoFormRef" :table="formData.table" />
      </el-tab-pane>
      <el-tab-pane label="字段信息" name="columnInfo">
        <column-info-form ref="columnInfoFormRef" :columns="formData.columns" />
      </el-tab-pane>
      <el-tab-pane label="生成信息" name="generateInfo">
        <generate-info-form
          ref="generateInfoFormRef"
          :table="formData.table"
          :columns="formData.columns"
        />
      </el-tab-pane>
    </el-tabs>
    <el-form>
      <div class="text-center mt-20px">
        <el-button :disabled="formLoading" type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="close(false)">返 回</el-button>
      </div>
    </el-form>
  </ContentWrap>
</template>

<script setup lang="ts">
import * as CodegenApi from '@/api/infra/codegen'
import { useTagsViewStore } from '@/stores/modules/tagsView'
import BasicInfoForm from './components/BasicInfoForm.vue'
import ColumnInfoForm from './components/ColumnInfoForm.vue'
import GenerateInfoForm from './components/GenerateInfoForm.vue'

defineOptions({ name: 'InfraCodegenEditTable' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { push, currentRoute } = useRouter() // 路由
const { delView } = useTagsViewStore()

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeName = ref('columnInfo')
const basicInfoFormRef = ref<InstanceType<typeof BasicInfoForm>>()
const columnInfoFormRef = ref<InstanceType<typeof ColumnInfoForm>>()
const generateInfoFormRef = ref<InstanceType<typeof GenerateInfoForm>>()
const formData = ref<CodegenApi.CodegenDetailVO>({
  table: {},
  columns: []
})

const getDetail = async () => {
  const id = currentRoute.value.query.id as unknown as number
  if (!id) return
  formLoading.value = true
  try {
    formData.value = await CodegenApi.getCodegenDetail(id)
  } finally {
    formLoading.value = false
  }
}

const submitForm = async () => {
  if (!unref(formData)) return
  if (await unref(basicInfoFormRef)?.validate()) return
  if (await unref(generateInfoFormRef)?.validate()) return
  formLoading.value = true
  try {
    await CodegenApi.updateCodegenTable(formData.value)
    message.success(t('common.updateSuccess'))
    close(true)
  } finally {
    formLoading.value = false
  }
}

const close = (reload: boolean) => {
  // 关闭当前tab
  delView(unref(currentRoute))
  // 返回代码生成列表
  push({
    path: '/infra/codegen',
    state: { reload }
  })
}

onMounted(() => {
  getDetail()
})
</script>

<style scoped lang="scss"></style>
